import React, { useState, useEffect, useRef, useCallback } from 'react'
import Webcam from 'react-webcam';
import { faceRecognition, faceBindPhone } from '../../../api/csy/api'
import '../css/login/face.less'
import { useNavigate } from 'react-router-dom';
import '../../../assets/icon/font_4845297_w692z3izwm/iconfont.css'


interface Props {
    changeShow: (val: number) => void
}

const FaceLogin: React.FC<Props> = ({ changeShow }) => {
    const [loginMessage, setLoginMessage] = useState<string>('')
    const [isRecognizing, setIsRecognizing] = useState<boolean>(false)
    const webcamRef = useRef<Webcam>(null)
    const navigate = useNavigate()
    const phone = sessionStorage.getItem('phone')

    //通过phone来进行绑定手机号
    const bindPhone = useCallback(async (imageSrc: string) => {
        const response = await faceBindPhone({ 
          base64: imageSrc, 
          phone: phone || undefined 
        })
        if (response.data.code === 200) {
            // 绑定成功后，跳转到首页 
            changeShow(0)
            setLoginMessage('人脸识别成功，请重新登录')
            sessionStorage.removeItem('phone')
        } else {
            setLoginMessage(response.data.message || '人脸识别失败，请重试。')
        }
    }, [phone]); // 依赖 phone 状态
    const captureFrame = useCallback(async () => {
        const imageSrc = webcamRef.current?.getScreenshot(); // 获取当前视频流截图
        if (imageSrc && !isRecognizing) {
            setIsRecognizing(true);
            try {
                if (phone) {
                    bindPhone(imageSrc); // 调用 bindPhone 函数
                } else {
                    const response = await faceRecognition({ base64: imageSrc });
                    console.log(response);

                    if (response.data.code === 200) {
                        localStorage.setItem('userId', response.data.data.data.phone)
                        localStorage.setItem('accessToken', response.data.data.accessToken)
                        localStorage.setItem('refreshToken', response.data.data.refreshToken)
                        // 登录成功，跳转到首页
                        setLoginMessage('登录成功');
                        navigate('/home/ErrorCaptured');
                        return;
                    } else {
                        setLoginMessage(response.data.message || '未识别到有效人脸，请重试。');
                    }
                }
            } catch (error) {
                console.log(error);
                setLoginMessage('登录失败，请重试。');
            } finally {
                setIsRecognizing(false);
            }
        }
    }, [isRecognizing, webcamRef, phone, navigate, bindPhone]); // 依赖 bindPhone 和其他外部状态

    //每隔一秒捕获一次视频帧
    useEffect(() => {
        const interval = setInterval(() => {
            captureFrame();
        }, 1000 * 3); // 每2秒捕获一次
        return () => clearInterval(interval);
    }, [captureFrame])

    const dian = (val: number) => {
        changeShow(val)
    }
    return (
        <>
            <div className='face'>
                <span style={{
                    fontSize: '2.5rem',
                    fontWeight: 'bold',
                    position: 'fixed',
                    right: '0',
                    /* 三角形裁剪 */
                    clipPath: 'polygon(100% 100%, 0% 0%, 100% 0%)',
                    /* 透明度 */
                    opacity: '0.5',
                }} className="iconfont icon-a-computerdiannaojisuanji aaa" onClick={() => dian(0)} ></span>
                <div className='_title'>
                    <p className='_title-text'>人脸识别</p>
                </div>
                <Webcam
                    audio={false}
                    ref={webcamRef}
                    screenshotFormat='image/jpeg'
                    className='_video'
                    videoConstraints={{
                        facingMode: 'user'
                    }}
                >
                </Webcam>

            </div >

        </>
    )
}

export default FaceLogin